package com.onlyphoto.onlymall.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.tabs.TabLayout;
import com.onlyphoto.onlymall.R;
import com.onlyphoto.onlymall.bean.AreaResult;
import com.onlyphoto.onlymall.bean.response.RegionBean2;
import com.onlyphoto.onlymall.mvp.view.adapter.RegionAdapter;
import com.onlyphoto.onlymall.utils.CenterLayoutManager;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Objects;


/**
 * 地址选择器
 *
 * Created by gaochujia on 2019-07-24.
 */
public class AreaPickerView extends PopupWindow implements View.OnClickListener, TabLayout.OnTabSelectedListener {

    private View mPopView;
    private ImageView close;
    private TabLayout tl_pick;
    private RecyclerView rv_area;

    private Activity mActivity;

    private CenterLayoutManager centerLayoutManager;

    //地址数据集合 数据源
    private RegionBean2 mAreaData;
    //地址数据集合 结果集
    private ArrayList<AreaResult> mResultList = new ArrayList<>();
    //地址数据集合 recyclerView展示数据集
    private ArrayList<AreaResult> mRvList = new ArrayList<>();
    //标示 用来判断是否为最后一级数据
    private boolean isLast = false;
    //标示 用来区分是列表item点击 还是tab点击
    private boolean itemClick = false;
    //当前选中的tab
    private int mTabCurrent = 0;

    private int lastPosition = 0;

    //上一级id
    private String nowID;

    private RegionAdapter adapter;
    //地址选择完成的监听
    private OnSelectFinishedListener mListener;

    public AreaPickerView(Context mContext, RegionBean2 mAreaData) {
        super(mContext);
        mActivity = (Activity) mContext;
        this.mAreaData = mAreaData;
        init(mContext);
        setPopupWindow();
    }

    //初始化
    private void init(Context context) {
        mPopView = LayoutInflater.from(context).inflate(R.layout.area_select, null);
        centerLayoutManager = new CenterLayoutManager(context);
        close = mPopView.findViewById(R.id.close);
        tl_pick = mPopView.findViewById(R.id.tl_area);
        rv_area = mPopView.findViewById(R.id.rv_area);
        adapter = new RegionAdapter();

        //tl_pick.post(() -> setIndicator(tl_pick, 20, 20));
    }

    //设置tab下划线宽度，在这个视图不实用，此处作为代码保存
    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        assert tabStrip != null;
        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        if (llTab != null) {
            for (int i = 0; i < llTab.getChildCount(); i++) {
                View child = llTab.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                params.leftMargin = left;
                params.rightMargin = right;
                child.setLayoutParams(params);
                child.invalidate();
            }
        }
    }

    private void setPopupWindow() {
        this.setContentView(mPopView);// 设置View

        // 点击其他区域关闭
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.setAnimationStyle(R.style.anim_bottom);

        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);// 设置弹出窗口的宽
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);// 设置弹出窗口的高
        this.setBackgroundDrawable(new ColorDrawable(0x00000000));// 设置背景透明
        Window window = mActivity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();

        //退出popupWindow时显示父控件原来的颜色
        this.setOnDismissListener(() -> {
            lp.alpha = 1.0f;
            window.setAttributes(lp);
            //将最后一个tab选中的item居中
            if (mTabCurrent == 2) {
                centerLayoutManager.smoothScrollToPosition(rv_area, new RecyclerView.State(), lastPosition);
            }

            if (isLast) {
                mListener.finished(mResultList);
            }
        });
        close.setOnClickListener(this);
        tl_pick.addOnTabSelectedListener(this);

        adapter.setOnSelectListener((position, id, name) -> {
            itemClick = true;
            int tabCount = tl_pick.getTabCount();

            //选择完成后 重新弹出选择器并点击时 循环删除旧tab（此时结果集的 size 和 tabCount一样）
            if (tabCount == mResultList.size()) {
                mResultList.remove(tabCount - 1);
            }

            //选择未完成时 重新点击新地址后  循环删除旧tab（此时结果集的 size 比 tabCount 少 1）
            if (mTabCurrent < tabCount - 1) {
                for (int i = 0; i < tabCount - 1 - mTabCurrent; i++) {
                    tl_pick.removeTabAt(tabCount - 1 - i);
                    mResultList.remove(tabCount - 2 - i);
                }
            }

            mResultList.add(new AreaResult(true, position, id, name));

            //设置tab文字
            Objects.requireNonNull(tl_pick.getTabAt(mTabCurrent)).setText(name);

            //此处调用getData是为了传id参数，如果不是最后一行就会调用onTabSelected再调用getData获取数据，如果是最后一行就返回并dismiss()
            nowID = id;
            getData(id, position,false);

        });
        rv_area.setLayoutManager(centerLayoutManager);
        rv_area.setAdapter(adapter);

        addTab();
    }

    @Override
    public void onClick(View v) {
        this.dismiss();
    }

    //tabLayout中某个tab选中的监听
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        mTabCurrent = tab.getPosition();

        if (!itemClick) {
            int position = 0;
            int tabCount = tl_pick.getTabCount();
            if (mTabCurrent == 0){
                nowID = "0";
            } else {
                nowID = mResultList.get(mTabCurrent - 1).getId();
            }
            if (mResultList.size() > 0) {
                if (mResultList.size() == tabCount) {
                    position = mResultList.get(mTabCurrent).getPosition();
                } else {
                    position = mResultList.get(mTabCurrent == tabCount - 1 ? 0 : mTabCurrent).getPosition();
                }
            }
            getData(nowID, position, true);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    //添加Tab
    private void addTab() {
        tl_pick.addTab(tl_pick.newTab().setText("请选择"), true);
    }

    /**
     * 网络获取数据
     *
     * @param position 当前选中的item的position 用来把选中的item移动到第一位置
     * @param onlyShow  用来判断点击的为item 还是tab   如果是item 则要添加tab
     */
    private void getData(String nowID, final int position, final boolean onlyShow) {
        isLast = false;

        if (nowID.equals("") || (!nowID.equals("0") && mTabCurrent == 0 && null == mAreaData.getCity_arr().get(nowID))
                || (itemClick && !nowID.equals("0") && mTabCurrent == 1 && null == mAreaData.getDistrict_arr().get(nowID))) {
            //没有数据了  改变标示
            isLast = true;
            itemClick = false;
        }

        //无数据标示成立，说明是最后一级
        if (isLast) {
            //选择完成后记录最后一个tab的position
            lastPosition = position;
            for (int i = 0; i < mRvList.size(); i++) {
                if (i == position) {
                    mRvList.get(i).setSelected(true);
                } else {
                    mRvList.get(i).setSelected(false);
                }
            }
            adapter.notifyDataSetChanged();

            this.dismiss();
            return;
        }
        //如果是点击item，则添加tab
        if (!onlyShow) {
            addTab();
        }

        mRvList.clear();

        if (mTabCurrent == 0) {
            for (int i = 0; i < mAreaData.getProvince_arr().size(); i++) {
                AreaResult a;
                if (i == position && mResultList.size() > 0) {
                    a = mResultList.get(0);
                } else {
                    a = new AreaResult(false, i, mAreaData.getProvince_arr().get(i).getProvince_id(), mAreaData.getProvince_arr().get(i).getProvince());
                }
                mRvList.add(a);
            }
        }
        if (mTabCurrent == 1) {
            for (int i = 0; i < mAreaData.getCity_arr().get(nowID).size(); i++) {
                AreaResult a;
                if (i == position && mResultList.size() > 1) {
                    a = mResultList.get(1);
                } else {
                    a = new AreaResult(false, i, mAreaData.getCity_arr().get(nowID).get(i).getCity_id(), mAreaData.getCity_arr().get(nowID).get(i).getCity());
                }
                mRvList.add(a);
            }
        }

        if (mTabCurrent == 2) {
            for (int i = 0; i < mAreaData.getDistrict_arr().get(nowID).size(); i++) {
                AreaResult a;
                if (i == position && mResultList.size() > 2) {
                    a = mResultList.get(2);
                } else {
                    a = new AreaResult(false, i, "", mAreaData.getDistrict_arr().get(nowID).get(i));
                }
                mRvList.add(a);
            }
        }

        adapter.setData(mRvList);

        //显示item为视图第一个
        if (onlyShow) {
            centerLayoutManager.smoothScrollToPosition(rv_area, new RecyclerView.State(), position);
        }
        itemClick = false;
    }

    public void setFinishedListener(OnSelectFinishedListener listener){
        this.mListener = listener;
    }

    public interface OnSelectFinishedListener{
        void finished(ArrayList<AreaResult> list);
    }
}
